// 轻量 PRNG（LCG）确保相同 seed 可复现
function makePrng(seed?: number) {
  let x = (typeof seed === 'number' ? Math.abs(seed) : Math.floor(Math.random() * 2 ** 31)) || 123456789
  return () => {
    x = (x * 1664525 + 1013904223) >>> 0
    return x / 0x100000000
  }
}

function pick<T>(arr: T[], rnd: () => number): T {
  return arr[Math.floor(rnd() * arr.length)]
}

// ===== 各平台/浏览器生成器 =====
function genWindowsChrome(rnd: () => number): string {
  const majors = [120, 121, 122, 123, 124, 125, 126]
  const major = pick(majors, rnd)
  const minor = 0
  const patch = 0
  const chrome = `${major}.0.${minor}.${patch}`
  return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chrome} Safari/537.36`
}

function genWindowsEdge(rnd: () => number): string {
  const majors = [120, 121, 122, 123, 124, 125, 126]
  const major = pick(majors, rnd)
  const minor = 0
  const patch = 0
  const chrome = `${major}.0.${minor}.${patch}`
  const edg = `${major}.0.${minor}.${patch}`
  return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chrome} Safari/537.36 Edg/${edg}`
}

function genMacChrome(rnd: () => number): string {
  const majors = [120, 121, 122, 123, 124, 125, 126]
  const major = pick(majors, rnd)
  const macMaj = pick(['13_5', '13_6', '14_0', '14_1'], rnd)
  const chrome = `${major}.0.0.0`
  return `Mozilla/5.0 (Macintosh; Intel Mac OS X ${macMaj}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chrome} Safari/537.36`
}

function genMacSafari(rnd: () => number): string {
  const macMaj = pick(['13_5', '13_6', '14_0', '14_1'], rnd)
  const version = pick(['16.3', '16.4', '16.5', '17.0', '17.1'], rnd)
  // Safari WebKit 版本常见为 605.1.15（保持稳定更真实）
  return `Mozilla/5.0 (Macintosh; Intel Mac OS X ${macMaj}) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${version} Safari/605.1.15`
}

function genLinuxChrome(rnd: () => number): string {
  const majors = [120, 121, 122, 123, 124, 125, 126]
  const major = pick(majors, rnd)
  const chrome = `${major}.0.0.0`
  return `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chrome} Safari/537.36`
}

function genAndroidChrome(rnd: () => number): string {
  const majors = [118, 119, 120, 121, 122, 123, 124]
  const major = pick(majors, rnd)
  const devices = [
    'Pixel 5',
    'Pixel 6',
    'Mi 10',
    'Mi 11',
    'Redmi Note 11',
    'HUAWEI P40',
    'SM-G9910',
    'SM-G9960',
    'VOG-AL10',
  ]
  const android = pick(['11', '12', '13'], rnd)
  const model = pick(devices, rnd)
  const chrome = `${major}.0.0.0`
  return `Mozilla/5.0 (Linux; Android ${android}; ${model}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chrome} Mobile Safari/537.36`
}

function geniOSSafari(rnd: () => number): string {
  const ios = pick(['15_7', '16_3', '16_4', '16_5', '17_0'], rnd)
  const version = pick(['15.6', '16.3', '16.4', '16.5', '17.0'], rnd)
  return `Mozilla/5.0 (iPhone; CPU iPhone OS ${ios} like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${version} Mobile/15E148 Safari/604.1`
}

function geniPadSafari(rnd: () => number): string {
  const ios = pick(['15_7', '16_3', '16_4', '16_5', '17_0'], rnd)
  const version = pick(['15.6', '16.3', '16.4', '16.5', '17.0'], rnd)
  return `Mozilla/5.0 (iPad; CPU OS ${ios} like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${version} Mobile/15E148 Safari/604.1`
}

// ===== 对外 API =====

/**
 * 生成更丰富的 UA（桌面/移动、Windows/macOS/Linux/Android/iOS，Chrome/Edge/Safari）。
 */
export function generateUserAgent(options?: {
  device?: 'desktop' | 'mobile' | 'any'
  platform?: 'windows' | 'mac' | 'linux' | 'android' | 'ios' | 'any'
  browser?: 'chrome' | 'edge' | 'safari' | 'any'
  seed?: number
}): string {
  const rnd = makePrng(options?.seed)
  const wantDevice = options?.device || 'any'
  const wantPlatform = options?.platform || 'any'
  const wantBrowser = options?.browser || 'any'

  interface Entry { device: 'desktop' | 'mobile', platform: 'windows' | 'mac' | 'linux' | 'android' | 'ios', browser: 'chrome' | 'edge' | 'safari', gen: (r: () => number) => string }
  const pool: Entry[] = [
    { device: 'desktop', platform: 'windows', browser: 'chrome', gen: genWindowsChrome },
    { device: 'desktop', platform: 'windows', browser: 'edge', gen: genWindowsEdge },
    { device: 'desktop', platform: 'mac', browser: 'chrome', gen: genMacChrome },
    { device: 'desktop', platform: 'mac', browser: 'safari', gen: genMacSafari },
    { device: 'desktop', platform: 'linux', browser: 'chrome', gen: genLinuxChrome },
    { device: 'mobile', platform: 'android', browser: 'chrome', gen: genAndroidChrome },
    { device: 'mobile', platform: 'ios', browser: 'safari', gen: geniOSSafari },
    { device: 'mobile', platform: 'ios', browser: 'safari', gen: geniPadSafari },
  ]

  const filtered = pool.filter(p =>
    (wantDevice === 'any' || p.device === wantDevice)
    && (wantPlatform === 'any' || p.platform === wantPlatform)
    && (wantBrowser === 'any' || p.browser === wantBrowser),
  )
  const candidates = filtered.length > 0 ? filtered : pool
  const picked = pick(candidates, rnd)
  return picked.gen(rnd)
}

// 兼容旧 API：Windows 桌面 Chrome
export function generateDesktopChromeUA(seed?: number): string {
  const rnd = makePrng(seed)
  return genWindowsChrome(rnd)
}

export function pickOrGenerateUA(preferred?: string): string {
  const v = String(preferred || '').trim()
  if (v)
    return v
  return generateUserAgent()
}

/**
 * 生成指定版本的 iOS Safari 移动端 UA（精确到主次版本）。
 * 示例：generateIOSMobileSafariUA({ device: 'iphone', major: 18, minor: 5 })
 */
export function generateIOSMobileSafariUA(args: { device?: 'iphone' | 'ipad', major: number, minor?: number }): string {
  const device = (args?.device || 'iphone').toLowerCase() as 'iphone' | 'ipad'
  const major = Math.max(10, Math.floor(args.major || 16))
  const minor = Math.max(0, Math.floor(args.minor || 0))
  const iosUnderscore = `${major}_${minor}`
  const versionDot = `${major}.${minor}`
  if (device === 'ipad') {
    return `Mozilla/5.0 (iPad; CPU OS ${iosUnderscore} like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${versionDot} Mobile/15E148 Safari/604.1`
  }
  return `Mozilla/5.0 (iPhone; CPU iPhone OS ${iosUnderscore} like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${versionDot} Mobile/15E148 Safari/604.1`
}
